import OSS from '@/common/aliyunOss/aliyun.js';
import SparkMD5 from '@/common/spark-md5.js'

function aliyunOss(Vue, vm) {
	// 阿里云OSS上传 
	/**
	 * type文件类型
	 * pathData 选择到的文件对象
	 * extension 后缀名
	 * file_path 文件名
	 */
	let aliyunOSSFileUpload = (type, type_name, pathData, file_path) => {
		// console.log('开始上传')
		return new Promise((resolve, reject) => {
			let extension = pathData.path.split('.')[1];
			let date = new Date;
			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let folder = year + "-" + month + "/";
			let aliyunFileKey = Date.parse(new Date()) + parseInt(Math.random() * (100000 - 10000 + 1) + 10000, 10);
			
			var spark = new SparkMD5.ArrayBuffer();
			spark.append(pathData);
			let md5 = spark.end();
			
			if(!uni.$u.test.isEmpty(file_path)) {
				folder = file_path + '/' + folder;
			} else {
				folder = 'wechat_icon' + '/' + folder;
			}
			
			uni.uploadFile({
				url: OSS.host,
				filePath: pathData.path,
				name: 'file',
				formData: {
					'key': folder + aliyunFileKey + '.' + extension,
					'policy': OSS.policyBase64,
					'OSSAccessKeyId': OSS.accessid,
					'success_action_status': '200',
					'signature': OSS.signature,
				},
				success: (res) => {
					// console.log(res);
					let data = {
						domain: OSS.host,
						extension: extension,
						file_name: aliyunFileKey,
						type: type,
						type_name: type_name,
						size: pathData.size,
						uri: "/" + folder + aliyunFileKey + '.' + extension,
						md5: md5,
						local_path: OSS.host + "/" + folder + aliyunFileKey + '.' + extension,
					};
					resolve(data);
				},
				fail: (err) => {
			
				},
				complete: (res) => {
					
				}
			});
		})
	};
	
	/**
	 * 上传到数据库保留资源数据
	 * type文件类型
	 * pathData 选择到的文件对象
	 * extension 后缀名
	 * file_path 文件名
	 */
	let aliyunOSSFileUploadAsset = (type, type_name, pathData, file_path) => {
		// console.log('开始上传')
		return new Promise((resolve, reject) => {
			aliyunOSSFileUpload(type, type_name, pathData, file_path).then(res => {
				vm.$u.post('/asset/add', res).then(data => {
					resolve(data);
				})
			})
		})
	};
	
	return {
		aliyunOSSFileUpload,
		aliyunOSSFileUploadAsset,
	};
}

export default aliyunOss
